﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.Remoting.Messaging;

namespace Elective1_kim_sequel
{
     class Database
    {
        private static OdbcConnection connection;
        private static string server;
        private static string database;
        private static string uid;
        private static string password;

        static Database()
        {
            Initialize();
        }

        private static void Initialize()
        {
            server = "localhost";
            database = "mydatabase";
            uid = "root";
            password = "";

            string connectionString =
                "Driver={MySQL ODBC 5.1 Driver}" +
                ";SERVER=" + server +
                ";DATABASE=" + database +
                ";UID=" + uid +
                ";PWD=" + password +
                ";";

            connection = new OdbcConnection(connectionString);
        }

        private static bool openConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (OdbcException ex)
            {
                switch (ex.ErrorCode)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;

                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again");
                        break;
                }
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        private static bool closeConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (OdbcException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public static DataTable Table(string sqlquery)
        {
            if (openConnection() == true)
            {
                try
                {
                    string query = sqlquery;
                    OdbcCommand cmd = new OdbcCommand(query, connection);
                    OdbcDataAdapter adap = new OdbcDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    adap.Fill(dt);
                    connection.Close();
                    return dt;
                }
                catch (OdbcException exception)
                {
                    MessageBox.Show(exception.Message, "Error" + exception.ErrorCode.ToString());
                    closeConnection();
                }
                return null;
            }
            else
            {
                return null;
            }
        }

        static void Query(string sqlquery)
        {
            
            string query = sqlquery;
            if (openConnection() == true)
            {
                try
                {
                    OdbcCommand cmd = new OdbcCommand();
                    cmd.CommandText = query;
                    cmd.Connection = connection;
                    cmd.ExecuteNonQuery();
                    closeConnection();
                }
                catch (OdbcException exception)
                {
                    MessageBox.Show(exception.Message, "Error" + exception.ErrorCode.ToString());
                }
            }
        }


         //Async Method

        private delegate void MyTaskWorkerDelegate(string files);
        private bool _myTaskIsRunning = false;

        public bool IsBusy
        {
            get { return _myTaskIsRunning; }
        }

        public static void Query_Async(string q)
        {
            Database db = new Database();
            db._query(q);
        }

        public void _query(string query)
        {
            MyTaskWorkerDelegate worker = new MyTaskWorkerDelegate(Query);
            AsyncCallback completedCallback = new AsyncCallback(Query_CompletedCallback);

            lock (_sync)
            {
                if (_myTaskIsRunning)
                    throw new InvalidOperationException("The control is currently busy.");

                AsyncOperation async = AsyncOperationManager.CreateOperation(null);
                worker.BeginInvoke(query, completedCallback, async);
                _myTaskIsRunning = true;
            }
        }

        private readonly object _sync = new object();

        private void Query_CompletedCallback(IAsyncResult ar)
        {            
            MyTaskWorkerDelegate worker = (MyTaskWorkerDelegate)((AsyncResult)ar).AsyncDelegate;
            AsyncOperation async = (AsyncOperation)ar.AsyncState;
            
            worker.EndInvoke(ar);
           
            lock (_sync)
            {
                _myTaskIsRunning = false;
            }
            
            AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null,false, null);
            async.PostOperationCompleted(
              delegate(object e) { OnMyTaskCompleted((AsyncCompletedEventArgs)e); },
              completedArgs);
        }

        public static event AsyncCompletedEventHandler Query_Completed;

        protected virtual void OnMyTaskCompleted(AsyncCompletedEventArgs e)
        {
            if (Query_Completed != null)
                Query_Completed(this, e);
        }


    }
}


